require 'rrb/parser'

module Evil
  class Class
    def initialize(class_node)
      @class_node = class_node
    end

    def include?(lineno)
      (@class_node.range.head.lineno..@class_node.range.tail.lineno).include?(lineno)
    end

    def is_testcase?
      super_class = @class_node.superclass.elements_id.collect(&:name).join('::')
      super_class == "Test::Unit::TestCase"
    end
  end

  class NullClass
    def is_testcase?
      false
    end
  end

  class OuterClassVisitor < RRB::Visitor
    def initialize(lineno)
      @lineno = lineno
      @outer_class = NullClass.new
    end

    def visit_class( namespace, class_node ) 
      clazz = Class.new(class_node)
      @outer_class = clazz if clazz.include?(@lineno)
    end

    attr_reader :outer_class
  end

  class RubyFile
    def initialize(path)
      @path = path
    end

    def load
      IO.popen("ruby #{@path} 2>&1")do |pipe|
        pipe.sync = true
        while(c = pipe.getc)
          yield c.chr
        end
      end
      @last_result = $?.exitstatus
    end

    def success_loaded?
      @last_result == 0
    end

    def in_testcase?(lineno)
      visitor = OuterClassVisitor.new(lineno)
      RRB::Parser.new.run(File.open(@path, 'r')).accept(visitor)
      visitor.outer_class.is_testcase?
    end

  end

end
